// pages/orders/cart.js
var app = getApp();
var currentShopId = 0;

Page({
    data: {
        is_empty: false,
        allChecked: false,
        choose: '编辑'
    },
    onLoad: function (options) {
        var that = this;
        this.setData({
            windowHeight: app.systemInfo.windowHeight
        })
        currentShopId = wx.getStorageSync('shop_id');
        //读取shop
        //读取购物车
        console.log(currentShopId)
        if (currentShopId) {
            var carts = wx.getStorageSync('carts');
            console.log(carts)
            app.func.req('shops/show', {
                id: currentShopId
            }, 'GET', function (res) {
                //TODO: refactor
            if(res.code=='error' && res.msg=='shop.close.blank'){
                wx.showToast({
                    title: '店铺已关闭',
                    image: '/images/fail.png',
                    duration: 2000
                });
                return;
            }             
                that.setData({
                    shop: res.result
                });
            }, {
                    'token': wx.getStorageSync('token')
                });

            if (!carts) {
                carts = []
            }
            var cartIndex;
            for (var i = 0; i < carts.length; i++) {
                if (carts[i].shopId == currentShopId) {
                    var cart = carts[i];
                    cartIndex = i;
                }
            }
            if (cartIndex >= 0 && cart.products.length > 0) {
                that.setData({
                    carts: carts,
                    cartIndex: cartIndex,
                    products: cart.products
                })
                that.selectAll()
            } else {
                //为空
                that.setData({
                    is_empty: true
                })
            }
        } else {
            that.setData({
                is_empty: true
            })
        }
    },

    loadCart: function () {
        //读取总价和数量
        var products = this.data.products;
        var count = 0;
        var total = 0;
        var allChekced = this.data.allChecked;
        for (var i = 0; i < products.length; i++) {
            if (products[i].specs.length == 0 && products[i].checked) {
                count += products[i].num;
                total = Number(total) + Number(products[i].num * products[i].price)
            } else if (products[i].specs.length > 0) {
                for (var j = 0; j < products[i].specs.length; j++) {
                    if (products[i].specs[j].checked) {
                        count += products[i].specs[j].num;
                        total = Number(total) + Number(products[i].specs[j].num * products[i].specs[j].price)
                    }
                }
            }
        }
        this.setData({
            total: Math.round(total * 100) / 100,
            count: count
        })
        this.saveCart()
    },
    Choose: function () {
        if (this.data.choose == '编辑')
            this.setData({
                choose: '完成'
            })
        else
            this.setData({
                choose: '编辑'
            })
    },
    Minus: function (e) {
        var that = this;
        var productId = e.target.dataset.id;
        var specIndex = e.target.dataset.index;
        var products = this.data.products;
        var total = this.data.total;
        var count = this.data.count;

        for (var i = 0; i < products.length; i++) {
            if (products[i].id == productId) {
                //购物车中存在，且数量大于1
                if (products[i].specs.length == 0) {
                    if (products[i].checked) {
                        count--;
                        total -= Number(products[i].price);
                    }
                    products[i].num--;
                    if (products[i].num == 0) {
                        products[i].num++;
                        return false;
                        //roducts.splice(i, 1);
                    }
                } else {
                    if (products[i].specs[specIndex].checked) {
                        count--;
                        total -= Number(products[i].specs[specIndex].price);
                    }
                    products[i].specs[specIndex].num--;
                    if (products[i].specs[specIndex].num == 0) {
                        var product_empty = true;
                        for (var j = 0; j < products[i].specs.length; j++) {
                            if (products[i].specs[j].num > 0) {
                                product_empty = false;
                            }
                        }
                    }
                    if (product_empty) {
                        products.splice(i, 1);
                    }
                }
            }
        }

        this.setData({
            products: products,
            total: Math.round(total * 100) / 100,
            count: count
        });
        this.saveCart();
    },
    Plus: function (e) {
        var productId = e.target.dataset.id;
        var specIndex = e.target.dataset.index;
        var products = this.data.products;
        var total = this.data.total;
        var count = this.data.count;
        var carts = this.data.carts;

        for (var i = 0; i < products.length; i++) {
            if (products[i].id == productId) {
                if (products[i].specs.length == 0) {
                    if (products[i].is_limit > 0 && products[i].limit_num < products[i].num + 1) {
                        wx.showToast({
                            title: '限购' + products[i].is_limit + '个',
                            image: '/images/fail.png',
                            duration: 2000
                        });
                        return false
                    }
                    if (products[i].checked) {
                        count++;
                        total += Number(products[i].price);
                    }
                    products[i].num++;

                } else {
                    if (products[i].is_limit > 0 && products[i].specs[specIndex].limit_num < products[i].specs[specIndex].num + 1) {
                        wx.showToast({
                            title: '该商品限购' + products[i].is_limit + '个',
                            image: '/images/fail.png',
                            duration: 2000
                        });
                        return false
                    }
                    if (products[i].specs[specIndex].checked) {
                        count++;
                        total += Number(products[i].specs[specIndex].price);
                    }
                    products[i].specs[specIndex].num++;
                }
            }
        }

        carts[this.data.cartIndex].products = products;

        this.setData({
            products: products,
            total: Math.round(total * 100) / 100,
            count: count
        });
        this.saveCart();
    },
    saveCart: function () {
        var carts = this.data.carts
        var cart = carts[this.data.cartIndex]
        cart.products = this.data.products;
        cart.count = this.data.count;
        cart.total = this.data.total;
        wx.setStorage({
            key: 'carts',
            data: carts
        })
        this.setData({
            carts: carts
        });
    },
    productsChange: function (e) {
        var productIndex = e.currentTarget.dataset.productindex;
        var specIndex = e.currentTarget.dataset.specindex;
        var products = this.data.products
        var product = products[productIndex];
        if (product.specs.length == 0) {
            product.checked = !product.checked
        } else {
            product.specs[specIndex].checked = !product.specs[specIndex].checked
        }
        this.setData({
            allChecked: this.data.allChecked ? false : false,
            products: products
        })
        this.loadCart()
    },
    selectAll: function () {
        var products = this.data.products
        console.log(products.length)
        var allChecked = !this.data.allChecked
        for (var i = 0; i < products.length; i++) {
            if (products[i].specs.length == 0) {
                products[i].checked = allChecked
            } else {
                products[i].specs.forEach(function (spec) {
                    spec.checked = allChecked
                })
            }
        }
        this.setData({
            allChecked: allChecked,
            products: products
        })
        this.loadCart()
    },
    deleteProduct: function () {
        var products = this.data.products
        var new_products = []
        var product_empty = true;
        for (var i = 0; i < products.length; i++) {
            if (products[i].specs.length == 0 && !products[i].checked) {
                new_products.push(products[i])
            } else if (products[i].specs.length > 0) {
                product_empty = true;
                products[i].specs.forEach(function (spec) {
                    if (spec.checked) {
                        spec.num = 0
                    } else if (spec.num > 0) {
                        product_empty = false
                    }
                })
                if (!product_empty) {
                    new_products.push(products[i])
                }
            }
        }
        this.setData({
            products: new_products
        })
        this.loadCart();
    },
    createOrder: function () {
        var products = this.data.products
        var new_products = []
        var product_empty = true;
        for (var i = 0; i < products.length; i++) {
            if (products[i].specs.length == 0 && products[i].checked) {
                new_products.push(products[i])
            } else if (products[i].specs.length > 0) {
                product_empty = true;
                products[i].specs.forEach(function (spec) {
                    if (!spec.checked) {
                        spec.num = 0
                    } else if (spec.num > 0) {
                        product_empty = false
                    }
                })
                if (!product_empty) {
                    new_products.push(products[i])
                }
            }
        }
        this.setData({
            products: new_products
        })
        this.loadCart();

        wx.navigateTo({
            url: '/pages/orders/order_confirm'
        });
    }
})